package com.ef.web.action;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;

import com.ef.constant.ConfirmMessage;
import com.ef.domain.Menu;
import com.ef.domain.Role;
import com.ef.service.MenuService;
import com.ef.service.RoleService;
import com.ef.util.CustomExample;

public class RoleAction extends BaseAction<Role> {

	private RoleService roleService;
	private MenuService menuService;

	private List<Menu> menus;

	private static final long serialVersionUID = 1L;
	protected final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory
			.getLog(RoleAction.class);

	@SuppressWarnings("serial")
	public String list() {

		this.listResult = roleService.findByExample(new CustomExample<Role>(this
				.getModel()) {

			public void appendCondition(Criteria criteria) {
				this.enableLike(MatchMode.ANYWHERE);
			}
		}, this.getStartIndex(), this.getPageSize());
		return LIST;
	}
	
	public String edit(){
		fetchMenuData();
		return EDIT;
	}
	private void fetchMenuData(){
		menus = menuService.findAll();
		String treeData = "";
		for(Menu menu:menus){
			treeData+="d.add("+menu.getId()+","+replace(menu.getParent())+",'"+menu.getName()+"','#');\n ";
		}
		getRequest().setAttribute("treeData", treeData);
	}
	
	private String replace(Menu parent){
		if(parent!=null)
			return parent.getId().toString();
		else 
			return "0";
	}
	public String save(){
		
		Role role =this.getModel();
		
		roleService.saveOrUpdate(role);
		
		this.setResult(ConfirmMessage.Role);
		fetchMenuData();
		return EDIT;
	}
	public String delete() {
		String ids = getRequest().getParameter("ids");
		String[] id = ids.split(",");
		for (String i : id) {
			roleService.delete(roleService.findById(Long.valueOf(i)));
		}

		return DELETE;
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public List<Menu> getMenus() {
		return menus;
	}

	public void setMenus(List<Menu> menus) {
		this.menus = menus;
	}

}
